package com.ltmonitor.web.controller.video;

import com.ltmonitor.entity.BasicData;
import com.ltmonitor.entity.GPSRealData;
import com.ltmonitor.entity.TerminalCommand;
import com.ltmonitor.entity.VehicleData;
import com.ltmonitor.service.IRealDataService;
import com.ltmonitor.service.IVideoFileItemService;
import com.ltmonitor.service.IVideoServerConfigService;
import com.ltmonitor.util.DateUtil;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.video.entity.VideoFileItem;
import com.ltmonitor.video.entity.VideoServerConfig;
import com.ltmonitor.web.controller.command.TerminalCommandAction;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.vo.VideoFile;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.aspectj.weaver.tools.cache.SimpleCacheFactory.path;

/**
 * 下发查询终端音视频资源列表命令
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/videoDownload")
public class VideoDownloadAction extends TerminalCommandAction {

	/**
	 * 录像文件记录
	 */
	@Resource
	private IVideoFileItemService videoFileItemService;


	@Autowired
	private IRealDataService realDataService;

	@RequestMapping("/view.action")
	public String view(long vehicleId, Model m) {
		m.addAttribute("vehicleId", vehicleId);
		return "/video/ftpUpload";
	}

	/**
	 * 发送控制上传指令
	 *
	 * @param vehicleId
	 * @param controlCmd 控制指令关键字 0暂停，1继续 2取消
	 * @param commandId  对应文件上传消息的Id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/controlUpload.action")
	public JsonMessage controlUpload(long vehicleId, int controlCmd, long commandId) {
		try {
			//获取上传指令的流水号
			TerminalCommand d = this.terminalCommandService.load(commandId);
			long serialNo = d.getSN();

			StringBuilder sb = new StringBuilder();
			sb.append(serialNo).append(";").append(controlCmd);
			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(0x9207);
			tc.setCmdData(sb.toString());
			tc.setVehicleId(vehicleId);
			SendCommand(tc);

			return json(true, tc.getEntityId());
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return json(false, ex.getMessage());
		}
	}

	@ResponseBody
	@RequestMapping("/ftpUploadByResourceId.action")
	public JsonMessage ftpUploadByResourceId(long resourceId, String taskCondition)
	{
		if(taskCondition == null)
			taskCondition = "0,1,2";
		try {
			VideoFileItem vi = this.videoFileItemService.load(resourceId);
			return this.sendRequest(vi.getVehicleId(), vi.getDataType(), vi.getStreamType(), vi.getAlarmStatus(), vi.getStoreType(), vi.getChannelId(),
					vi.getStartDate(), vi.getEndDate(), taskCondition);
		}catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return json(false, ex.getMessage());
		}
	}


	/**
	 * 下发查询资源列表指令
	 *
	 * @param vehicleId
	 * @param channel
	 * @param startDate
	 * @param endDate
	 * @param alarmStatus 报警标志
	 * @param mediaType   音视频资源类型
	 * @param streamType  码流类型
	 * @param storeType   存储器类型
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/sendRequest.action")
	public JsonMessage sendRequest(long vehicleId, int mediaType, int streamType, String alarmStatus, int storeType,
								   int channel, Date startDate, Date endDate, String taskCondition) {

		try {
			long alarm = 0;
			if (StringUtil.isNullOrEmpty(alarmStatus) == false) {
				String[] strAlarms = alarmStatus.split(",");
				byte[] alarmArray = new byte[64];
				for (String strAalrm : strAlarms) {
					int bit = Integer.parseInt(strAalrm);
					alarmArray[bit] = 1;
				}

				StringBuilder sb = new StringBuilder();
				for (byte b : alarmArray) {
					sb.append(b);
				}
				sb.reverse();
				alarm = Long.valueOf(sb.toString(), 2); // 将位数组转换为字节值
			}
			return this.sendRequest(vehicleId,mediaType,streamType, alarm, storeType, channel, startDate, endDate, taskCondition);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return json(false, ex.getMessage());
		}
	}

	/**
	 * 下发查询资源列表指令
	 *
	 * @param vehicleId
	 * @param channel
	 * @param startDate
	 * @param endDate
	 * @param alarm 报警标志
	 * @param mediaType   音视频资源类型
	 * @param streamType  码流类型
	 * @param storeType   存储器类型
	 * @return
	 */
	private JsonMessage sendRequest(long vehicleId, int mediaType, int streamType, long alarm, int storeType,
								   int channel, Date startDate, Date endDate, String taskCondition) {

		try {
			long condition = StringUtil.convertBitStringToInt(taskCondition,8) ;
			String ftpServerIp = this.getVideoServerConfig().getFtpServerIp();
			int ftpServerPort = this.getVideoServerConfig().getFtpPort();
			String ftpUserName = this.getVideoServerConfig().getFtpUserName();
			String password = this.getVideoServerConfig().getFtpPassword();

			VehicleData vd = vehicleDataService.load(vehicleId);
			String subDirectory = vd.getSimNo() + "_" + channel + "_" + mediaType + "_" + DateUtil.toStringByFormat(new Date(),"yyMMddHHmmss");
			String ftpFilePath = subDirectory ;// this.getVideoServerConfig().getFtpPath();

			StringBuilder sb = new StringBuilder();
			sb.append(ftpServerIp).append(';').append(ftpServerPort).append(';').append(ftpUserName).append(';').append(password).append(';')
					.append(ftpFilePath).append(';')
					.append(channel).append(';')
					.append(DateUtil.datetimeToString(startDate)).append(';')
					.append(DateUtil.datetimeToString(endDate)).append(';')
					.append(alarm).append(';').append(mediaType).append(';')
					.append(streamType).append(';').append(storeType).append(';').append(condition);

			TerminalCommand tc = new TerminalCommand();
			tc.setCmdType(0x9206);
			tc.setCmdData(sb.toString());
			tc.setVehicleId(vehicleId);
			SendCommand(tc);

			VideoFileItem vi = new VideoFileItem();
			vi.setAlarmStatus(alarm);
			vi.setChannelId((byte) channel);
			vi.setDataType((byte) mediaType);
			vi.setStartDate(startDate);
			vi.setEndDate(endDate);
			vi.setStoreType((byte) storeType);
			vi.setStreamType((byte) streamType);
			vi.setCommandId(tc.getEntityId());
			vi.setVehicleId(tc.getVehicleId());
			vi.setPlateNo(tc.getPlateNo());
			vi.setFileSource(VideoFileItem.FROM_FTP);
			vi.setFilePath(ftpFilePath);
			GPSRealData rd = realDataService.get(tc.getSimNo());
			if(rd != null)
			{
				vi.setLongitude1(rd.getLongitude());
				vi.setLatitude1(rd.getLatitude());
			}
			videoFileItemService.save(vi);

			return json(true, tc.getEntityId());
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return json(false, ex.getMessage());
		}
	}


	/**
	 * 根据指令ID，获取终端返回的多媒体记录数据列表
	 *
	 * @param commandId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getVideoResourceList.action")
	public JsonMessage getVideoResourceList(long commandId) {
		try {
			TerminalCommand tc = getTerminalCommand(commandId);
			BasicData bd = getBasicDataService().getBasicDataByCode(
					tc.getStatus(), "TCommandStatus");
			String status = bd != null ? bd.getName() : "";
			Map result = new HashMap();
			result.put("status", status);
			if (TerminalCommand.STATUS_SUCCESS.equals(tc.getStatus())) {
				List<VideoFileItem> data = this.videoFileItemService.getVideoFileItemListByCommandId(commandId);
				result.put("data", data);
				return json(true, result);
			} else if (TerminalCommand.STATUS_NEW.equals(tc.getStatus()) == false
					&& TerminalCommand.STATUS_PROCESSING.equals(tc.getStatus()) == false) {
				return json(true, status);
			} else {
				return json(false, status);
			}
		} catch (Exception ex) {
			log.error(ex.getMessage());
			log.error(ex.getStackTrace());
			return json(false, "查询时发送错误:" + ex.getMessage());
		}
	}


	@RequestMapping("downloadVideoFile")
	public ResponseEntity<byte[]> download(String filePath) throws IOException {
		String strDir = this.getVideoServerConfig().getFtpPath() + "\\" + filePath;
		File file = searchFile(strDir);
		//String path="F:\\rtp120180102140113.txt";
		//File file=new File(path);
		HttpHeaders headers = new HttpHeaders();
		String fileName = new String(file.getName().getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题
		headers.setContentDispositionFormData("attachment", fileName);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
				headers, HttpStatus.CREATED);
	}

	public static File searchFile(String path) {// 递归查找包含关键字的文件
		File d = new File(path);
		if (d.isDirectory()) {
			File[] fs = d.listFiles();
			for (int i = 0; i < fs.length; i++) {
				File f = fs[i];
				String fileName = f.getName();
				if (fileName.endsWith(".264") || fileName.endsWith(".avi") || fileName.endsWith(".mp4")) {
					return f;

				}
			}
		}else
		{
			return d;
		}
		return null;

	}
}
